package com.gitee.zycra.union.api.common.validator;

import com.gitee.zycra.union.api.common.annotation.EnumCheck;
import com.gitee.zycra.union.api.common.enums.CommonEnum;
import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @author zycra
 */
@Slf4j
public class EnumValidator implements ConstraintValidator<EnumCheck, Integer> {

    private boolean required;

    private Class<? extends CommonEnum> clazz;

    private static final String METHOD_NAME = "getByCode";

    @Override
    public void initialize(EnumCheck constraintAnnotation) {
        this.required = constraintAnnotation.required();
        this.clazz = constraintAnnotation.value();
    }

    @Override
    public boolean isValid(Integer code, ConstraintValidatorContext constraintValidatorContext) {
        if (!required && code == null) {
            return true;
        }
        try {
            return clazz.getMethod(METHOD_NAME, Integer.class).invoke(null, code) != null;
        } catch (Exception e) {
            log.error("没有找到通过枚举值获取枚举信息的方法", e);
            return false;
        }
    }
}
